package com.chen.springboot.service.impl;

import com.chen.springboot.mapper.mongoMapper.PlayersMapper;
import com.chen.springboot.vo.Players;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author chenchao
 * @date 2022/7/2 23:10
 */
@Service
public class PlayersServiceImpl {

    @Autowired
    private PlayersMapper playersMapper;

    @Autowired
    private MongoTemplate mongoTemplate;


    public Page<Players> findPage(int page, int size, String country, String displayName) {
//        return playersMapper.findAll( PageRequest.of(page - 1, size));
        Sort sort = Sort.by(Sort.Direction.ASC, "_id");
        Pageable pageRequest = PageRequest.of(page - 1, size, sort);
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("country").regex(country),
                Criteria.where("displayName").regex(displayName));

        query.addCriteria(criteria);
        long count = mongoTemplate.count(query, Players.class);
        if (count != 0) {
            List<Players> list = mongoTemplate.find(query.with(pageRequest), Players.class);

            return new PageImpl(list, pageRequest, count);
        } else {
            return playersMapper.findAll(PageRequest.of(page - 1, size));
        }


//        return playersMapper.findAll( PageRequest.of(page - 1, size));
    }


    //    分页2
    public Page<Players> findPage2(int page, int size, String country, String displayName) {
//        return playersMapper.findAll( PageRequest.of(page - 1, size));
        Sort sort = Sort.by(Sort.Direction.ASC, "_id");
        Pageable pageRequest = PageRequest.of(page - 1, size, sort);
        Query query = new Query();

        Criteria criteria1 = Criteria.where("country").is(country);
        Criteria criteria2 = Criteria.where("displayName").regex(displayName);

        if (!"".equals(country)) {
            query.addCriteria(criteria1);
        }
        if (!"".equals(displayName)) {
            query.addCriteria(criteria2);
        }


        long count = mongoTemplate.count(query, Players.class);

        List<Players> list = mongoTemplate.find(query.with(pageRequest), Players.class);

        return new PageImpl(list, pageRequest, count);


//        return playersMapper.findAll( PageRequest.of(page - 1, size));
    }
}
